package cli;


public class TableLayout {
    private String[] header;
    private String[][] table;
    private int[] gap;

    private static boolean isChinese(char c) {
        return 0x4a00 <= c && c <= 0x9fa5;
    }

    private static int getWidth(char c) {
        return isChinese(c) ? 2 : 1;
    }

    private static int getWidth(String str) {
        int width = 0;
        for (int i = 0; i < str.length(); ++i) {
            width += getWidth(str.charAt(i));
        }
        return width;
    }

    public TableLayout(String[] header, String[][] table) {
        this.header = header;
        this.table = table;
        gap = new int[header.length];
        for (int i = 0; i < header.length; ++i) {
            gap[i] = getWidth(header[i]);
            for (String[] strings : table) {
                gap[i] = Math.max(gap[i], getWidth(strings[i]));
            }
        }
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < header.length; ++j) {
            sb.append(header[j]);
            for (int k = 0; k < gap[j] - getWidth(header[j]); ++k) {
                sb.append(' ');
            }
            sb.append('\t');
        }
        for (int i = 0; i < table.length; ++i) {
            sb.append('\n');
            for (int j = 0; j < table[i].length; ++j) {
                sb.append(table[i][j]);
                for (int k = getWidth(table[i][j]); k < gap[j]; ++k) {
                    sb.append(' ');
                }
                sb.append('\t');
            }
        }
        if (table.length == 0)
            sb.append("\n\t空");
        return sb.toString();
    }
}
